package cn.nuomi.shop.api.controller;

import cn.nuomi.shop.api.vo.BaseRespVO;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date: 2021/4/26 15:17
 * @description: 业务数据处理
 */
public class BaseServlet extends HttpServlet {
    protected void successResp(HttpServletResponse resp, Object data) throws IOException {
        //构建标准返回内容
        BaseRespVO result = new BaseRespVO();
        result.setStatus(BaseRespVO.StatusType.SUCCESS.getValue());
        result.setData(data);
        //转换为json
        String json = JSON.toJSONString(result);
        //返回结果设置编码
        resp.setContentType("text/html;charset=UTF-8");
        //json写入到返回数据区域
        resp.getWriter().write(json);
    }

    protected void errorResp(HttpServletResponse resp, String errorMsg) throws IOException {
        BaseRespVO result = new BaseRespVO();
        result.setStatus(BaseRespVO.StatusType.FAILED.getValue());
        result.setMsg(errorMsg);
        String json = JSON.toJSONString(result);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(json);
    }
}
